let observer = null;

function startObserving() {
  if (observer) {
    observer.disconnect();
  }

  observer = new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      if (mutation.type === "childList") {
        const addedNodes = mutation.addedNodes;
        for (const node of addedNodes) {
          if (node.nodeType === Node.ELEMENT_NODE) {
            if (isAlertDetailNode(node)) {
              injectIframe();
              extractAlertContent(node);
              return;
            }
          }
        }
      }
    }
  });

  observer.observe(document.body, { childList: true, subtree: true });
}

function isAlertDetailNode(node) {
  // 这里需要根据您的页面结构来判断是否是告警详情节点
  // 例如，可以检查特定的类名、ID 或其他属性
  return (
    node.classList.contains("alert-detail") ||
    node.id === "alertModal" ||
    node.querySelector(".alert-content")
  );
}

function injectIframe() {
  if (!document.getElementById("security-agent-iframe")) {
    const iframe = document.createElement("iframe");
    iframe.id = "security-agent-iframe";
    iframe.src = chrome.runtime.getURL("popup.html");
    iframe.style.cssText = `
      position: fixed;
      top: 0;
      right: 0;
      width: 30%;
      height: 100%;
      border: none;
      z-index: 2147483647;
      box-shadow: -2px 0 5px rgba(0,0,0,0.2);
    `;
    document.body.appendChild(iframe);
  } else {
    const iframe = document.getElementById("security-agent-iframe");
    iframe.style.display = "block";
  }
}

function extractAlertContent(node) {
  // Check if chrome is defined and has the runtime property
  if (typeof chrome !== "undefined" && chrome.runtime) {
    const content = node.innerText;
    chrome.runtime.sendMessage({ action: "newAlertContent", content: content });
  } else {
    console.warn("Chrome runtime environment not detected.");
  }
}

startObserving();
